package com.ml4ai.backend.services.mappers;

import com.ml4ai.backend.consts.Const;
import com.ml4ai.backend.domain.Ticket;
import com.ml4ai.backend.dto.TicketDTO;
import com.ml4ai.backend.repository.TicketRepositroy;
import com.ml4ai.backend.repository.UserRepo;
import com.ml4ai.backend.utils.Bean2Bean;
import com.ml4ai.backend.utils.PropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by uesr on 2018/9/16.
 */
@Component
public class TicketMapper extends BaseMapper<Ticket, TicketDTO> {

    @Autowired
    TicketRepositroy ticketRepositroy;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRepo userRepo;

    @Override
    public Ticket newEntity() {
        return new Ticket();
    }

    @Override
    public TicketDTO newDTO() {
        return new TicketDTO();
    }

    @Override
    public Ticket find(Long id) {
        return ticketRepositroy.getOne(id);
    }

    @Override
    public void entity2dto(Ticket entity, TicketDTO dto) {
        new Bean2Bean().addPropMapper(
                new PropertyMapper<>("user", userMapper::e2d),
                new PropertyMapper<>("user.id", "userId")
        ).copyProperties(entity, dto);
    }

    @Override
    public void dto2entity(TicketDTO dto, Ticket entity) {
        new Bean2Bean().addExcludeProp(Const.getNotCopyAuditFields()).addExcludeProp("user").copyProperties(dto, entity);
        Long userId = Bean2Bean.getFirstNoNullVal(dto, "userId", "user.id");
        if (userId != null) {
            entity.setUser(userRepo.getOne(userId));
        } else {
            entity.setUser(null);
        }
    }
}
